package jprint.jfx.http;

import javax.annotation.Nonnull;
import jprint.base.AppContext;
import jprint.base.http.AbstractRequestHandler;
import jprint.base.http.Http;
import jprint.base.label.LabelService;

/**
 * @author zw-zheng
 * Created on 2021-02-04
 */
class LabelHandler extends AbstractRequestHandler {

    private final LabelService labelService;

    LabelHandler(@Nonnull AppContext appContext) {
        labelService = LabelService.getInstance(appContext);
    }

    @Override public boolean handle(Http.HttpRequest request, Http.HttpResponse response) {
        String uri = request.uri();
        Http.Method method = request.method();
        if (uri.equals("/api/label") || uri.startsWith("/api/label/")) {
            if (method == Http.Method.GET) {
                if (isFileGet(request)) {
                    String filename = uri.substring(1 + uri.lastIndexOf('/'));
                    response.setContentType(contentTypeOf(uri))
                        .setStatus(200)
                        .write(labelService.getFile(filename));
                    return true;
                }
            } else if (method == Http.Method.POST) {
                labelService.post(request.bodyParams());
                response.setContentType("application/x-javascript")
                    .setStatus(200)
                    .write(SUCCESS_JSON);
                return true;
            }
        }
        return false;
    }
}
